package com.benjaminwan.read.free.ui.main

import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.airbnb.mvrx.*
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.fragment.BaseMainFragment
import com.benjaminwan.read.free.base.viewmodel.state
import com.benjaminwan.read.free.model.bean.ContentAttach.Companion.getFullUrl
import com.benjaminwan.read.free.model.enums.NetRetState
import com.benjaminwan.read.free.net.RetrofitFactory
import com.benjaminwan.read.free.ui.MainActivity
import com.benjaminwan.read.free.ui.net.NetViewModel
import com.benjaminwan.read.free.utils.*
import com.google.android.material.navigation.NavigationView
import com.orhanobut.logger.Logger
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog

class MainFragment : BaseMainFragment() {
    private val mainVM by activityViewModel(MainViewModel::class)
    private val netVM by activityViewModel(NetViewModel::class)

    private val fileUri: Uri? by argsNullable()

    private val toolbar: Toolbar
        get() = (requireActivity() as MainActivity).binding.toolbar

    private val navigationView: NavigationView
        get() = (requireActivity() as MainActivity).binding.navigationView

    private val drawerLayout: DrawerLayout
        get() = (requireActivity() as MainActivity).binding.drawerLayout

    private val userNameTv: TextView
        get() = navigationView.getHeaderView(0).findViewById(R.id.userNameTv)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val uri = fileUri ?: return
        runWithPermissions(Permission.READ_EXTERNAL_STORAGE) {
            loadFromUri(uri, mainVM)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initNavigationView()
        initNavigation()
        setHasOptionsMenu(true)
    }

    override fun onPrepareOptionsMenu(menu: Menu) {
        val id = findNavController().currentDestination?.id
        if (id == R.id.scriptFragment || id == R.id.groupFragment || id == R.id.actionFragment || id == R.id.threadFragment) {
        } else {
            val isConnected = mainVM.state.connected
            menu.findItem(R.id.menu_connect).isVisible = !isConnected
            menu.findItem(R.id.menu_disconnect).isVisible = isConnected
        }
        super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean =
        when (item.itemId) {
            R.id.menu_discoverable -> {
                val discoverableIntent =
                    Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)
                discoverableIntent.putExtra(
                    BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300
                )
                startActivity(discoverableIntent)
                true
            }
            R.id.menu_connect -> {
                //Logger.i("action_connect")
                val plugDev = mainVM.state.plugDev
                if (plugDev != null) {
                    mainVM.connect()
                } else {
                    showXToastError("当前没有配对主机，无法连接!")
                }
                true
            }
            R.id.menu_disconnect -> {
                //Logger.i("action_disconnect")
                mainVM.disConnect()
                true
            }
            R.id.menu_unplug -> {
                Logger.i("action_unplug")
                val builder = AlertDialog.Builder(requireContext())
                builder.setTitle(R.string.unplug_title).setMessage(R.string.unplug_message)
                builder.setPositiveButton(
                    android.R.string.yes
                ) { dialog, which -> mainVM.unplug() }
                builder.setNegativeButton(android.R.string.no, null)
                builder.create().show()
                true
            }
            else -> {
                super.onOptionsItemSelected(item)
            }
        }

    override fun onStop() {
        mainVM.saveSP()
        super.onStop()
    }

    private fun initNavigation() {
        findNavController().addOnDestinationChangedListener { controller, destination, arguments ->
            when (destination.id) {
                R.id.actionFragment, R.id.groupFragment -> {
                    setLeftAction(true)
                }
                else -> {
                    setLeftAction(false)
                }
            }
        }
    }

    private fun setLeftAction(isBack: Boolean) {
        if (isBack) {
            toolbar.setNavigationIcon(R.drawable.navigation_back_white)
            toolbar.setNavigationOnClickListener {
                findNavController().navigateUp()
            }
        } else {
            toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp)
            toolbar.setNavigationOnClickListener {
                drawerLayout.openDrawer(GravityCompat.START)
            }
        }
    }

    private fun initNavigationView() {
        navigationView.setupWithNavController(findNavController())
        navigationView.getHeaderView(0).setOnClickListener { view ->
            MaterialDialog.Builder(requireContext())
                .title("退出登录？")
                .content("确认退出当前登录用户，并清除保存的登录信息？\n")
                .positiveText(android.R.string.ok)
                .negativeText(android.R.string.cancel)
                .onNegative { dialog, which ->
                    dialog.dismiss()
                }
                .onPositive { dialog, which ->
                    netVM.clearLoginInfo()
                    RetrofitFactory.clearCookies()
                    RetrofitFactory.clearLoginResult()
                    findNavController().navigate(R.id.compatFragment)
                    dialog.dismiss()
                }
                .show()
            drawerLayout.closeDrawers()
        }
        /*navigationView.inflateMenu(R.menu.drawer)
        navigationView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.drawer_app_settings -> {
                    findNavController().navigate(R.id.compatibilityFragment)
                }
                else -> {
                }
            }
            drawerLayout.closeDrawers()
            false
        }*/

    }

    override fun invalidate() = withState(mainVM, netVM) { main, net ->
        requireActivity().invalidateOptionsMenu()
        if (net.username.isNotEmpty()) {
            userNameTv.text = net.username
        }
        val plugDevName = if (main.plugDev != null) {
            if (main.plugDev.name.isNullOrEmpty()) {
                main.plugDev.address
            } else {
                main.plugDev.name
            }
        } else {
            "未配对"
        }
        val readyMsg = if (main.appReady) {
            "准备就绪"
        } else {
            "未初始化"
        }
        val connected = if (main.connected) {
            "已连接"
        } else {
            "未连接"
        }
        /*val bootMode = if (main.bootMode) {
            "boot"
        } else {
            "report"
        }*/
        toolbar.subtitle = "$readyMsg 设备[$plugDevName] $connected"
        when (net.versionRequest) {
            is Success -> {
                val ret = net.versionRequest()
                netVM.resetVersionRequest()
                Logger.i("$ret")
                if (ret != null) {
                    if (ret.state == NetRetState.RE_LOGIN) {
                        showXToastInfo("登陆信息失效，正在自动重新登陆!")
                        netVM.login()
                    } else if (ret.state == NetRetState.SUCCESS && ret.needUpdate) {
                        val versionInfo = if (ret.info.isNotEmpty()) "版本信息：${ret.info}" else ""
                        MaterialDialog.Builder(requireContext())
                            .title("版本升级")
                            .content("当前版本:${requireContext().getAppVersionName()}\n发现新版本:${ret.lastVersion}\n是否转到浏览器下载？\n$versionInfo")
                            .negativeText("取消")
                            .positiveText("去浏览器下载")
                            .onPositive { dialog, which ->
                                val intent = getUrlViewIntent(getFullUrl(ret.url))
                                startActivity(intent)
                                dialog.dismiss()
                            }
                            .show()
                    }
                }
            }
            is Fail -> {
                netVM.resetVersionRequest()
            }
            else -> {
            }
        }
    }

    override fun canBackPressed(): Boolean {
        return when (findNavController().currentDestination?.id) {
            R.id.actionFragment, R.id.groupFragment -> {
                false
            }
            else -> {
                true
            }
        }
    }

    companion object {
        const val TAG = "MainFragment"
        fun arg(uri: Uri?): Bundle {
            val args = Bundle()
            args.putParcelable(MvRx.KEY_ARG, uri)
            return args
        }
    }

}